package cc.wanforme.chipmunity.system.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import cc.wanforme.chipmunity.common.bean.WebResponse;
import cc.wanforme.chipmunity.common.consts.PassageEnum;
import cc.wanforme.chipmunity.common.consts.ReplyEnum;
import cc.wanforme.chipmunity.system.mapper.InnerReplyMapper;
import cc.wanforme.chipmunity.system.mapper.PassageMapper;
import cc.wanforme.chipmunity.system.mapper.ReplyMapper;
import cc.wanforme.chipmunity.system.mapper.user.UserMapper;
import cc.wanforme.chipmunity.system.po.InnerReply;
import cc.wanforme.chipmunity.system.po.Passage;
import cc.wanforme.chipmunity.system.po.Reply;
import cc.wanforme.chipmunity.system.po.user.User;
import cc.wanforme.chipmunity.system.service.interfaces.InnerReplyService;

/**
 * @author wanne
 * 2019年8月17日
 * 
 */
@Service
public class InnerReplyServiceImpl implements InnerReplyService {

	@Autowired
	private InnerReplyMapper innerReplyMapper;
	
	@Autowired
	private ReplyMapper replyMapper;

	@Autowired
	private PassageMapper passageMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public WebResponse saveInnerReply(InnerReply innerReply) {
		if(innerReply.getReplyId() == null ) {
			return WebResponse.fail("未知回复");
		}
		
		if(StringUtils.isBlank(innerReply.getContent())) {
			return WebResponse.fail("请填写内容");
		}
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication == null) {
			return WebResponse.fail("未登录");
		}
		
		Reply reply = replyMapper.selectReply(innerReply.getReplyId());
		if(reply == null || !reply.getState().equals( ReplyEnum.STATE_ON.getState())) {
			return WebResponse.fail("回复楼不见了");
		}
		
		Passage passage = passageMapper.selectPassage(reply.getPassageId());
		if(passage == null || !passage.getState().equals( PassageEnum.STATE_ON.getState())) {
			return WebResponse.fail("文章不见了");
		}
		
		
		Long ireplyId = innerReply.getIreplyId()!=null? innerReply.getIreplyId():0;
		
		User user = userMapper.selectUserByUsername(authentication.getName());
		InnerReply innerReply_persistent = new InnerReply(innerReply.getReplyId(), user.getId(), ireplyId, innerReply.getContent());
		innerReplyMapper.insertInnerReply(innerReply_persistent);
		return WebResponse.success("回复成功");
	}
	
	
	@Override
	public WebResponse updateInnerReply(InnerReply innerReply) {
		if(innerReply.getId() == null) {
			return WebResponse.fail("未知回复");
		}
		
		innerReplyMapper.updateInnerReply(innerReply);
		return WebResponse.success("更新成功");
	}
	
	@Override
	public WebResponse removeInnerReply(Long id) {
		innerReplyMapper.deleteInnerReply(id);
		return WebResponse.success("删除成功");
	}
	
}
